package com.ruoyi.web.easyExcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.framework.web.domain.excel.FileInfo;
import com.ruoyi.web.mapper.FileInfoMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
public class NoModelDataListener2 extends AnalysisEventListener<Map<Integer, String>> {

    /**原文件目录*/
    private String directory;

    /**筛选后文件目录加文件名*/
    private String directoryOfFiltedAndName;

    /**筛选条件*/
    private List<String> numbers;

    /**用来保存表头*/
    private List<List<String>> headList =new ArrayList<>();

    /**用来保存筛选出的数据*/
    List<Map<Integer,String>> dataList=ListUtils.newArrayList();

    FileInfoMapper fileInfoMapper;

    FileInfo fileInfo;

    /**条件列的index*/
    private int index;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public NoModelDataListener2(String directory, String directoryOfFilted, FileInfo fileInfo, FileInfoMapper fileInfoMapper,List<String> numbers) {
        this.directory = directory;
        this.directoryOfFiltedAndName =directoryOfFilted;
        this.fileInfoMapper=fileInfoMapper;
        this.fileInfo=fileInfo;
        this.numbers=numbers;
    }

    /**
     * 这里会一行行的返回头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("----------==========正在筛选{}==========----------\n",
                directoryOfFiltedAndName.substring(directoryOfFiltedAndName.lastIndexOf("/")));
        log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
        //解析到头数据并保存
        Map<Integer, String> headMap2= ConverterUtils.convertToStringMap(headMap, context);
        String[] s={"渠道编码","受理局向","渠道编号","代理商编码","渠道"};
        List<String> names= Arrays.asList(s);
        headMap2.forEach((k,v)->{
            List<String> head=new ArrayList<>();
            head.add(v);
            headList.add(head);
            if(names.contains(v)){
                index=k;
            }

        });
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
//        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        for (String number : numbers) {
            if(StringUtils.isNotBlank(data.get(index))&&data.get(index).equals(number)){
                dataList.add(data);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        File file=new File(directoryOfFiltedAndName);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try (ExcelWriter excelWriter = EasyExcel.write(file).build()) {
            WriteSheet writeSheet0 = EasyExcel.writerSheet(0).sheetName("内容").head(headList).build();
            excelWriter.write(dataList, writeSheet0);
            excelWriter.finish();
        }
        fileInfo.setIsFilted("1");
        fileInfoMapper.updateById(fileInfo);

        log.info("---------=========={}筛选完成！==========----------\n",
                directoryOfFiltedAndName.substring(directoryOfFiltedAndName.lastIndexOf("/")));
    }
}
